为什么程序执行完 p = p->next 语句后报内存错误?

来源:百度知道 编辑:UC知道 时间:2024/06/30 09:39:30
部分代码:
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;

void showList( LNode L )
{
LinkList p;
p = &L;
cout << "线性表为:" << endl;
for (int i = 0; i < 3; ++i)
{
p = p->next; // 每次执行到这就报错
cout << p->next;
}
}
回答一和二楼:我之前用的也是 while (p != NULL) 但一直报错,后来为了找出问题就用了for。
回答三楼:写错了。= =!

多学学基础吧,void showList( LNode L ) 这个子函数型参是什么?是一个节点!而链表节点本身就是一个指针,这个型参是不能正确接受的。还有你那个初始化链表函数估计也有问题,全贴出来吧,这样才好帮你解决

#include<iostream>
using namespace std;

#define ElemType char

void CreateList_L(LinkList *L)
{
char ch;
LNode *p;
*L=(LinkList)malloc(sizeof(LNode));
(*L)->next=NULL;
cout<<"请连续输入链表数据,并以回车结束!"<<endl;
cin.get(ch);
// getchar();
while(ch!='\n')//回车值为10
{
p=(LNode*)malloc(sizeof(LNode));
p->data=ch;
p->next=(*L)->next;
(*L)->next=p;
cin.get(ch);
}
}

void Display(LinkList L)
{
LNode *p;
p=L->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}

void main()
{
LinkList L=NULL;
CreateList_L(&L);
Display(L);
}

可能你的链表L少于4个结点(包括头